<!--
 * @Description: 登录组件
 * @Author: feichong124
 * @Date: 2023-02-19 20:55:17
 * @LastEditors: feichong124
 * @LastEditTime: 2023-03-01 15:34:08
 -->
<template>
  <div id="myLogin">
    <client-only>
      <el-dialog title="登录" width="300px" center v-model="isLogin">
        <el-form :model="LoginUser"  :rules="rules"  status-icon ref="ruleFormRef" class="demo-ruleForm">
          <el-form-item prop="name">
            <el-input prefix-icon="el-icon-user-solid" placeholder="请输入账号" v-model="LoginUser.name" ></el-input>
          </el-form-item>
          <el-form-item prop="pass">
            <el-input prefix-icon="el-icon-view" type="password" placeholder="请输入密码" v-model="LoginUser.pass" ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="Login" style="width:100%;">登录</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </client-only>
  
  </div>
</template>

<script> 
import { mapActions, mapState } from 'pinia' 
import { useCounterStore } from '../stores/user'
import { useNuxtApp } from "#app";

export default {
  name: "MyLogin",
  data () {
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      // console.log('value->' ,value)
      // console.log('callback',callback  ,'value->' ,value)
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
      if (userNameRule.test(value)) {
        // this.$refs.ruleFormRef.validateField("name"); // 加入报错 内存溢出
        return callback();
      } else {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z]\w{5,17}$/;
      if (passwordRule.test(value)) {
        // this.$refs.ruleFormRef.validateField("pass"); // 加入报错 内存溢出
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    return {
      LoginUser: {
        name: "admin123456",
        pass: "admin123456"
      },
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        name: [{ validator: validateName, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }]
      }
    };
  },
  created( )  {

  },
  setup( ) {
    let nuxtApp = useNuxtApp()
    return {  ElNotificationError :  nuxtApp.$ElNotificationError ,
      ElNotificationSuccess:  nuxtApp.$ElNotificationSuccess
    } 
  },
  mounted () {

  },
  computed: {
    ...mapState(useCounterStore, ['getShowLogin', 'showLogin']),
    // 获取vuex中的showLogin，控制登录组件是否显示

    isLogin: {
      get () {
        return this.showLogin;
      },
      set (val) {
        this.$refs["ruleFormRef"].resetFields();
        this.setShowLogin(val);
      }
    }
  },
  methods: {
    ...mapActions(useCounterStore, ['setUser', 'setShowLogin']), 
    Login () {
      // admin123/admin123456   
      // // 通过element自定义表单校验规则，校验用户输入的用户信息
    
      this.$refs["ruleFormRef"].validate(async valid => {
        //如果通过校验开始登录
        if (valid) {

          const { data, pending, error, refresh } = await useFetch(() => `/api/users/login`,
            {
              method: 'post',
              body: {
                userName: this.LoginUser.name,
                password: this.LoginUser.pass
              }
            }
          )
          if (data.value.code === "001") {
            // 隐藏登录组件
            this.isLogin = false;
            // 登录信息存到本地
            let user = JSON.stringify(data.value.user);
            localStorage.setItem("user", user);
            // 登录信息存到vuex
            this.setUser(data.value.user);
            // 弹出通知框提示登录成功信息
            this.ElNotificationSuccess(data.value.msg);
          } else {
            // 清空输入框的校验状态
            this.$refs["ruleFormRef"].resetFields();
            // 弹出通知框提示登录失败信息
            this.ElNotificationError(data.value.msg);
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style>
</style>